package com.roobo.demo;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.roobo.mqttsdk.MQTTInterface;
import com.roobo.mqttsdk.manager.DeviceInfoManager;
import com.roobo.mqttsdk.manager.PlayControllerManager;
import com.roobo.mqttsdk.manager.ResourceManager;
import com.roobo.mqttsdk.manager.MQTTManager;
import com.roobo.mqttsdk.manager.ResultInterface;
import com.roobo.vui.RError;
import com.roobo.vui.api.InitListener;
import com.roobo.vui.api.VUIApi;
import com.roobo.vui.api.tts.RTTSPlayer;
import com.roobo.vui.business.auth.entity.UserInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;

/**
 * 注意：MQTT初始化，先初始化VUI sdk获取clientId以及token，参数share给MQTTSDK进行初始化，demo采用广播的方法来传递数据。
 * MQTTSDK demo虽然依赖了VUI sdk，但不代表开发者的原有项目已引入了VUI sdk，MQTT实现还需要再次依赖，demo只是为演示share参数的方才采取这样的操作。
 * demo 才有采用动态广播接收是为了编码方便，开发者建议使用静态广播接收VUI sdk的广播
 */


public class MainActivity extends AppCompatActivity implements MQTTInterface, View.OnClickListener {

    public static final String TAG = MainActivity.class.getSimpleName();
    /**
     * roobo分配【保密】AGENT_ID
     */
    public static final String AGENT_ID = "4Yjk3MTJmOTM3MDg";

    /**
     * roobo分配【保密】AGENT_TOKEN
     */
    public static final String AGENT_TOKEN = "0ba355905ac741e366c1ba1bd9be668d4400";


    /**
     * roobo分配【保密】PUBLIC_KEY
     */
    private final static String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEnxQMF65T+Pwl3DIR2nDQZKLspJ5I0NDAfO22BEGf7DM6/si0SV+HQI6fuvEnQmSPLKm8EZm8kG52IszxUXUoT1MxJq3MY0DqTauQhxKQ8gpiSEX59q6YA36j/xI99ZlEHEbE8QMQXCAD/7Jj4LVaLFSDWbKu3TLf3hW1ItlOVQIDAQAB";

    /**
     * roobo 测试
     */
    public static final String PRODUCT_NAME = "luqiya";

    /**
     * roobo分配【保密】
     */
    public static final String PRODUCT_ID = "49360";
    /**
     * roobo 测试
     */
    public static final String MODEL = "luqiya";
    /**
     * roobo 测试
     */
    public static final String SOLUTION = "luqiya";
    /**
     * roobo 测试
     */
    public static final String FWVERSION = "luqiya";
    /**
     * roobo 测试
     */
    public static final String TRACK_LIST_ID = "1327000";
    /**
     * roobo 测试
     */
    public static final String TRACK_ID = "268952873";

    public static final String CLIENT_ID = "clientID";
    public static final String TOKEN = "token";

    public static final String VUI_SDK_INIT_COMPLETE = "com.roobo.VUISdk.InitComplete";

    public static final String CMD_SYNC_TRACK_LIST = "onReceiveSyncTrackList";
    public static final String CMD_QUERY_TRACK_LIST_INFO = "onReceiveTrackListInfo";
    public static final String CMD_QUERY_TRACK_INFO = "onReceiveTrackInfo";
    public static final String CMD_SET_VOLUME = "setVolume";
    public static final String VOLUME_VALUE = "value";
    public static final String CMD_REBOOT = "reboot";
    public static final String CMD_POWER_OFF = "powerOff";
    public static final String CMD_UN_BINDE = "unbind";
    public static final String CMD_ALARM = "alarm";
    public static final String ALARM_SOUND = "sound";
    public static final String CMD_CUSTOM_COMMAND = "customCommand";
    public static final String CMD_ON_EVENT = "onEvent";

    public static final int INIT_VUI_SDK_COMPLETE = 0;
    public static final int SYNC_TRACK_LIST = 1;
    public static final int QUERY_TRACK_LIST_INFO = 2;
    public static final int QUERY_TRACK_INFO = 3;
    public static final int TO_VOICE_CHAT_ACTIVITY = 4;
    public static final int TO_PLAY_ACTIVITY = 5;
    public static final int GET_DEVICE_INFO = 6;
    public static final int CONNECT_MQTT_SUCCESS = 7;
    public static final int CONNECT_MQTT_FAIL = 8;
    public static final int SET_VOLUME = 9;

    public static final int REBOOT = 10;
    public static final int UN_BINDE = 11;
    public static final int POWER_OFF = 12;
    public static final int ALARM = 13;
    public static final int CUSTOM_COMMAND = 14;
    public static final int ON_EVENT = 15;

    private ProgressDialog mProgressDialog;
    private AlertDialog mResultDialog;

    private Button mInitServiceBtn;
    private Button mSendPlayCmdBtn;
    private Button mSendPlayModeBtn;
    private Button mSyncTrackListBtn;

    private Button mQueryTrackListInfoBtn;
    private Button mQueryTrackInfoBtn;
    private Button mCollectTrackBtn;

    private Button mPlayTrackBtn;
    private Button mSendVoiceFileBtn;
    private Button mReportDeviceInfoBtn;

    private Button mUpdateNetworkBtn;
    private Button mReleaseServiceBtn;
    private Button mGetDeviceInfoBtn;

    private Button mBindUserBtn;

    private LinearLayout mFunctionPartLl;
    private Button mSendCustomMessageBtn;

    private MyHandler mHandler;
    private AudioManager mAudioManager;

    /**
     * 静态内部类
     */
    static class MyHandler extends Handler {
        private WeakReference<MainActivity> mWeakReference;

        public MyHandler(MainActivity activity) {
            mWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mWeakReference.get() == null) {
                return;
            }
            mWeakReference.get().dismissProgressDialog();
            Log.d(TAG, "handleMessage what:" + msg.what);

            switch (msg.what) {
                case INIT_VUI_SDK_COMPLETE:
                    String clientId = msg.getData().getString(CLIENT_ID);
                    String token = msg.getData().getString(TOKEN);
                    mWeakReference.get().sendInitVuiSdkCompleteBroadcast(clientId, token);
                    break;
                case SYNC_TRACK_LIST:
                case QUERY_TRACK_LIST_INFO:
                case QUERY_TRACK_INFO:
                    mWeakReference.get().showResultDialog(msg.obj.toString());
                    break;
                case TO_VOICE_CHAT_ACTIVITY:
                    mWeakReference.get().toVoiceChatActivity(msg.obj.toString());
                    break;
                case TO_PLAY_ACTIVITY:
                    mWeakReference.get().toPlayActivity(msg.obj.toString());
                    break;
                case GET_DEVICE_INFO:
                    mWeakReference.get().toQRcodeActivity(msg.obj.toString());
                    break;
                case CONNECT_MQTT_SUCCESS:
                    mWeakReference.get().setInitMQTTCompleteView();
                    break;
                case CONNECT_MQTT_FAIL:
                    mWeakReference.get().reInitMQTT();
                    break;
                case SET_VOLUME:
                    mWeakReference.get().reportVolume(msg.obj.toString());
                    break;
                case REBOOT:
                case UN_BINDE:
                case POWER_OFF:
                case CUSTOM_COMMAND:
                case ON_EVENT://接收消息，做相应的业务处理
                    mWeakReference.get().showResultDialog(msg.obj.toString());
                    break;
                case ALARM:
                    mWeakReference.get().handleAlarm(msg.obj.toString());
                    break;
            }
        }
    }

    /***
     * VUI SDK初始化成功接收器
     */
    private BroadcastReceiver vuiSdkInitReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String sn = intent.getStringExtra(CLIENT_ID);
            String token = intent.getStringExtra(TOKEN);
            Log.d(TAG, "onReceive  sn:" + sn + " token:" + token);
            MQTTManager.ParamsBuilder builder = new MQTTManager.ParamsBuilder();
            builder.setDeviceName(sn);//参数必传
            builder.setDeviceToken(token);//参数必传
            builder.setProductionInfo(AGENT_ID, AGENT_TOKEN);//参数必传
            MQTTManager.getInstance().initService(builder, MainActivity.this);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle(getResources().getString(R.string.main_activity_title));
        initViews();
        mHandler = new MyHandler(this);
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        applyPermission(this);
        registerVUISdkReceiver();
    }

    private void initViews() {
        mInitServiceBtn = findViewById(R.id.init_service_btn);
        mSendPlayCmdBtn = findViewById(R.id.send_play_cmd_btn);
        mSendPlayModeBtn = findViewById(R.id.send_play_mode_btn);

        mSyncTrackListBtn = findViewById(R.id.sync_track_list_btn);
        mQueryTrackListInfoBtn = findViewById(R.id.query_track_list_info_btn);
        mQueryTrackInfoBtn = findViewById(R.id.query_track_info_btn);

        mCollectTrackBtn = findViewById(R.id.collect_track_btn);
        mPlayTrackBtn = findViewById(R.id.play_track_btn);
        mSendVoiceFileBtn = findViewById(R.id.send_voice_file_btn);

        mReportDeviceInfoBtn = findViewById(R.id.report_device_info_btn);
        mUpdateNetworkBtn = findViewById(R.id.update_network_btn);
        mReleaseServiceBtn = findViewById(R.id.release_service_btn);

        mBindUserBtn = findViewById(R.id.bind_user_btn);

        mGetDeviceInfoBtn = findViewById(R.id.get_device_info_btn);
        mSendCustomMessageBtn = findViewById(R.id.send_custom_message_btn);
        mFunctionPartLl = findViewById(R.id.function_part_ll);

        mInitServiceBtn.setOnClickListener(this);
        mSendPlayCmdBtn.setOnClickListener(this);
        mSendPlayModeBtn.setOnClickListener(this);

        mSyncTrackListBtn.setOnClickListener(this);
        mQueryTrackListInfoBtn.setOnClickListener(this);
        mQueryTrackInfoBtn.setOnClickListener(this);

        mCollectTrackBtn.setOnClickListener(this);
        mPlayTrackBtn.setOnClickListener(this);
        mSendVoiceFileBtn.setOnClickListener(this);

        mReportDeviceInfoBtn.setOnClickListener(this);
        mUpdateNetworkBtn.setOnClickListener(this);
        mReleaseServiceBtn.setOnClickListener(this);

        mBindUserBtn.setOnClickListener(this);

        mGetDeviceInfoBtn.setOnClickListener(this);
        mSendCustomMessageBtn.setOnClickListener(this);
    }

    /***
     * 连接状态回调用
     * @param code
     */
    @Override
    public void onState(int code) {//非主线程
        Log.d(TAG, "onState code=" + code);
        if (code == MQTTManager.CONNECT_SUBSCRIBE_SUCCESS) {//MQTT初始化成功
            mHandler.sendEmptyMessage(CONNECT_MQTT_SUCCESS);
        } else if (code == MQTTManager.CONNECT_FAIL) {//断网需要重联
            mHandler.sendEmptyMessage(CONNECT_MQTT_FAIL);
        } else {
            Toast.makeText(MainActivity.this.getApplicationContext(), "失败 code=" + code, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 消息推送回调
     *
     * @param message
     */
    @Override
    public void onMessage(String message) {//非主线程
        Log.i(TAG, "onMessage message=" + message);
        if (!TextUtils.isEmpty(message)) {
            JSONObject object;
            String cmd = null;
            Message msg = Message.obtain();
            try {
                object = new JSONObject(message);
                cmd = object.getString(PlayActivity.CMD_TAG);
            } catch (JSONException e) {
                e.printStackTrace();
                Log.d(TAG, "onMessage e.getLocalizedMessage:" + e.getLocalizedMessage());
            }
            msg.obj = message;
            if (CMD_SYNC_TRACK_LIST.equals(cmd)) {//同步专辑
                msg.what = SYNC_TRACK_LIST;
            } else if (CMD_QUERY_TRACK_LIST_INFO.equals(cmd)) {//查询资源列表
                msg.what = QUERY_TRACK_LIST_INFO;
            } else if (CMD_QUERY_TRACK_INFO.equals(cmd)) {//查询资源信息
                msg.what = QUERY_TRACK_INFO;
            } else if (VoiceChatActivity.CMD_PLAY_VOICE.equals(cmd) || VoiceChatActivity.CMD_SHOW_TEXT_NO_TTS.equals(cmd)) {//公众号微聊
                msg.what = TO_VOICE_CHAT_ACTIVITY;
            } else if (PlayActivity.CMD_DEMAND_MUSIC_ONLINE.equals(cmd) || PlayActivity.CMD_BACKWARD.equals(cmd) || PlayActivity.CMD_FORWARD.equals(cmd)
                    || PlayActivity.CMD_PAUSE.equals(cmd)
                    || PlayActivity.CMD_RESUME.equals(cmd)) {//播放指定专辑，下一首，上一首、暂停、恢复
                msg.what = TO_PLAY_ACTIVITY;
            } else if (CMD_SET_VOLUME.equals(cmd)) {//设置音量
                msg.what = SET_VOLUME;
            } else if (CMD_REBOOT.equals(cmd)) {//重启系统 设备端收到该消息后重启系统。
                msg.what = REBOOT;
            } else if (CMD_UN_BINDE.equals(cmd)) {//收到解绑消息，清空wifi连接信息，用户信息，缓存，恢复设备设置到出厂设置
                msg.what = UN_BINDE;
            } else if (CMD_POWER_OFF.equals(cmd)) {//关闭系统 设备端收到该消息后关闭系统
                msg.what = POWER_OFF;
            } else if (CMD_ALARM.equals(cmd)) {//闹钟 用户通过手机端等在云端设置一个闹钟，在闹钟提醒时间到之后，云端向设备端推送相关消息
                msg.what = ALARM;
            } else if (CMD_CUSTOM_COMMAND.equals(cmd)) {//自定义消息，设备端和手机端相互发送自定义消
                msg.what = CUSTOM_COMMAND;
            } else if (CMD_ON_EVENT.equals(cmd)) {//事件消息，服务器处理相关事件后给设备端返回相关结果
                msg.what = ON_EVENT;
            }
            mHandler.sendMessage(msg);
        }
    }

    private void sendInitVuiSdkCompleteBroadcast(String clientID, String token) {
        Intent mIntent = new Intent(VUI_SDK_INIT_COMPLETE);
        mIntent.putExtra(CLIENT_ID, clientID);
        mIntent.putExtra(TOKEN, token);
        //发广播通知可以初始化MQTT
        MainActivity.this.sendBroadcast(mIntent);
    }

    private void toVoiceChatActivity(String message) {
        Intent mIntent = new Intent(this, VoiceChatActivity.class);
        mIntent.putExtra(VoiceChatActivity.MESSAGE, message);
        startActivity(mIntent);
        dismissResultDialog();
    }

    private void toPlayActivity(String message) {
        Intent mIntent = new Intent(this, PlayActivity.class);
        mIntent.putExtra(PlayActivity.MESSAGE, message);
        startActivity(mIntent);
        dismissResultDialog();
    }

    private void toQRcodeActivity(String message) {
        Intent mIntent = new Intent(MainActivity.this, QRCodeActivity.class);
        mIntent.putExtra(QRCodeActivity.MESSAGE, message);
        startActivity(mIntent);
    }

    private void setInitMQTTCompleteView() {
        mInitServiceBtn.setVisibility(View.GONE);
        mFunctionPartLl.setVisibility(View.VISIBLE);
    }

    private void reInitMQTT() {
        VUIApi.getInstance().release();
        MQTTManager.getInstance().releaseService();
        iniVUISdk();
    }

    /**
     * 收到该消息后将百分比音量转化为系统音量后设置设备音量，并将百分比音量上报到
     * 服务器。系统音量 = (int)(系统最大音量 * value/100)
     *
     * @param message
     */
    private void reportVolume(String message) {
        showResultDialog(message);
        int percentage = 0;
        try {
            JSONObject object = new JSONObject(message);
            percentage = object.getInt(VOLUME_VALUE);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d(TAG, "setVolume e.getLocalizedMessage:" + e.getLocalizedMessage());
        }
        Log.d(TAG, "setVolume percentage:" + percentage);
        int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        Log.d(TAG, "setVolume max:" + max);
        int value = max * percentage / 100;
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, value, AudioManager.FLAG_PLAY_SOUND);//调整音乐声
        DeviceInfoManager.getInstance().setVolume(percentage);
        DeviceInfoManager.getInstance().sendDeviceInfo(new ResultInterface() {
            @Override
            public void onResult(int code, String message) {
                Log.d(TAG, "setVolume code:" + code);
            }
        });
        Log.d(TAG, "setVolume value:" + value);
    }

    private void handleAlarm(String message) {
        showResultDialog(message);
        String sound = "";
        try {
            JSONObject object = new JSONObject(message);
            sound = object.getString(ALARM_SOUND);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d(TAG, "setVolume e.getLocalizedMessage:" + e.getLocalizedMessage());
        }
        if (!TextUtils.isEmpty(sound))//播放闹钟音
            MyMediaPlayer.getInstance().prepare(sound);
    }

    /**
     * 动态申请权限
     *
     * @param mActivity
     */
    public static void applyPermission(Activity mActivity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Log.d(TAG, "applyPermission");
            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.READ_PHONE_STATE}, 1);
        }
    }

    /**
     * 注册VUI sdk 初始化成功广播
     */
    public void registerVUISdkReceiver() {
        IntentFilter filter = new IntentFilter(VUI_SDK_INIT_COMPLETE);
        registerReceiver(vuiSdkInitReceiver, filter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.init_service_btn://初始化
                iniVUISdk();
                break;
            case R.id.send_play_mode_btn://上报播放模式
                PlayControllerManager.getInstance().sendPlayMode(PlayControllerManager.PlayMode.PLAY_MODE_RANDOM);
                Toast.makeText(this, getResources().getString(R.string.report_success), Toast.LENGTH_SHORT).show();
                break;
            case R.id.sync_track_list_btn://同步专辑
                showProgressDialog();
                ResourceManager.getInstance().syncTrackList();
                break;
            case R.id.query_track_list_info_btn://查询资源列表
                showProgressDialog();
                ResourceManager.getInstance().queryTrackListInfo(TRACK_LIST_ID);
                break;
            case R.id.query_track_info_btn://查询资源信息
                showProgressDialog();
                ResourceManager.getInstance().queryTrackInfo(TRACK_LIST_ID, TRACK_ID);
                break;
            case R.id.collect_track_btn://收藏资源
                ResourceManager.getInstance().collectTrack(TRACK_LIST_ID, TRACK_ID);
                Toast.makeText(this, getResources().getString(R.string.collect_success), Toast.LENGTH_SHORT).show();
                break;
            case R.id.send_play_cmd_btn://播放控制
            case R.id.play_track_btn://播放指定专辑
                Toast.makeText(this, getResources().getString(R.string.loading_resource), Toast.LENGTH_SHORT).show();
                PlayControllerManager.getInstance().playTrackList(TRACK_LIST_ID);
                break;
            case R.id.send_voice_file_btn://发送语音
                startActivity(new Intent(this, VoiceChatActivity.class));
                break;
            case R.id.get_device_info_btn://获取设备信息
                showProgressDialog();
                MQTTManager.getInstance().getWechatDeviceInfo(PRODUCT_NAME, PRODUCT_ID, MODEL, SOLUTION, FWVERSION, new ResultInterface() {
                    @Override
                    public void onResult(int code, String message) {//非主线程
                        Log.d(TAG, "getWechatDeviceInfo onResult code：" + code + " message:" + message);
                        Message msg = Message.obtain();
                        msg.what = GET_DEVICE_INFO;
                        msg.obj = message;
                        mHandler.sendMessage(msg);
                    }
                });
                break;
            case R.id.report_device_info_btn://上报设备信息
                startActivity(new Intent(this, ReportDeviceInfoActivity.class));
                break;
            case R.id.bind_user_btn://绑定设备
                MQTTManager.getInstance().bindUser("rt:03370e62d5a7564ca3ca22b29020e4f1", new ResultInterface() {
                    @Override
                    public void onResult(int i, String s) {
                        Log.d(TAG,"i:"+i+" s:"+s);
                    }
                });
                break;
            case R.id.update_network_btn://更新网络状态，即断网以后，主动联网操作，不等待自动重连
                MQTTManager.getInstance().updateNetwork();
                Toast.makeText(MainActivity.this, getResources().getString(R.string.update_success), Toast.LENGTH_SHORT).show();
                break;
            case R.id.send_custom_message_btn://发送自定义消息/设备事件/统计事件
                startActivity(new Intent(this, SendCustomActivity.class));
                break;
            case R.id.release_service_btn://释放MQTT
                finish();
                break;
        }
    }

    /**
     * 初始化VUI sdk
     */
    public void iniVUISdk() {
        Log.d(TAG, "iniVUISdk");
        showProgressDialog();
        UserInfo userInfo = new UserInfo();
        userInfo.setDeviceID(getDeviceID()); //必须设置此字段
        userInfo.setAgentID(AGENT_ID); //必须设置此字段
        userInfo.setPublicKey(PUBLIC_KEY); //必须设置此字段
        VUIApi.getInstance().setLogLevel(5);
        final VUIApi.InitParam.InitParamBuilder builder = new VUIApi.InitParam.InitParamBuilder();
        builder.setEnv(VUIApi.EnvType.ENV_ONLINE)//请根据分配的Appid配置环境
                .setUserInfo(userInfo)  //设置用户信息，必须设置
                .addOfflineFileName("test_offline") //设置离线词文件，必须设置
                .setAudioGenerator(new CustomAndroidAudioGenerator())//配置音频源
                .setVUIType( VUIApi.VUIType.MANUAL);  //设置交互方式，AUTO（唤醒后采用VAD进行断句） MANUAL(手动断句)
        VUIApi.getInstance().init(this, builder.build(), new InitListener() {
            @Override
            public void onSuccess() {
                Message message = Message.obtain();
                //获取clientID token
                String clientID = VUIApi.getInstance().getVUIParam(VUIApi.VUIParam.VUI_PARAM_GET_CLIENT_ID);
                String token = VUIApi.getInstance().getVUIParam(VUIApi.VUIParam.VUI_PARAM_GET_TOKEN);
                Log.d(TAG, "init   clientID:" + clientID + " token:" + token);
                Bundle bundle = new Bundle();
                bundle.putString(CLIENT_ID, clientID);
                bundle.putString(TOKEN, token);
                message.setData(bundle);
                message.what = INIT_VUI_SDK_COMPLETE;
                mHandler.sendMessage(message);
            }

            @Override
            public void onFail(RError rError) {
                Log.d(TAG, "init rError  code:" + rError.getFailCode() + " detail:" + rError.getFailDetail());
                Toast.makeText(MainActivity.this.getApplicationContext(), rError.getFailDetail(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取设备唯一标识符，分为两种方式：
     * 1 预分配并生产线烧录方式，直接将分配的SN号赋值给deviceID；
     * 2 通过唯一标识符在线注册方式，获取设备的唯一标识符赋值给deviceID；
     *
     * @return
     */
    private String getDeviceID() {
        return getDeviceSerialNO();
    }

    /**
     * 获取设备的唯一标识符，此函数做为参考，不保证返回标识符的唯一性，开发者需要根据自身设备的特性自己实现
     *
     * @return
     */
    private String getDeviceSerialNO() {
        String serial = "";
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
        } catch (Exception ignored) {
        }
        if (TextUtils.isEmpty(serial)) {
            serial = Build.SERIAL;
        }
        return serial;
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setTitle(getResources().getString(R.string.dialog_title));
            mProgressDialog.setMessage(getResources().getString(R.string.dialog_message));
        }
        if (!mProgressDialog.isShowing())
            mProgressDialog.show();
    }

    private void dismissProgressDialog() {
        if (!MainActivity.this.isFinishing() && mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void showResultDialog(final String result) {
        if (mResultDialog == null) {
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
            mBuilder.setTitle(getResources().getString(R.string.result_dialog_message));
            mResultDialog = mBuilder.create();
        }
        mResultDialog.setMessage(result);
        if (!mResultDialog.isShowing()) {
            mResultDialog.show();
        }
    }

    private void dismissResultDialog() {
        if (!MainActivity.this.isFinishing() && mResultDialog != null && mResultDialog.isShowing())
            mResultDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (MQTTManager.getInstance().isRunning()) {
            VUIApi.getInstance().release();
            MQTTManager.getInstance().releaseService();
        }
        unregisterReceiver(vuiSdkInitReceiver);
        dismissProgressDialog();
        dismissResultDialog();
        System.exit(0);//必须执行
    }

    public static String generateSoundwaveStr(String wifiName, String wifiPwd, String myId, String security, String hidden) {
        StringBuilder builder = new StringBuilder();

        builder.append("v1#");

        if (wifiName != null) {
            builder.append(encode(wifiName));
        }

        builder.append('#');
        if (wifiPwd != null) {
            builder.append(encode(wifiPwd));
        }

        builder.append('#');
        if (myId != null) {
            builder.append(encode(myId));
        }

        builder.append('#');
        if (security != null) {
            builder.append(encode(security));
        }

        builder.append('#');
        if (hidden != null) {
            builder.append(encode(hidden));
        }

        return builder.toString();
    }

    private static String encode(String str) {
        return str.replace("/", "//")
                .replace("\\", "\\\\")
                .replace("#", "/#");
    }

}
